package com.googlecode.simpleqms

class EmployeeService {
    static transactional = true

    def getList(params) {
        def selectedProject = Project.get(params.get('projectId').trim())
        return Employee.findAllByProject(selectedProject).collect {
            [
                    id: "Emp_${it.id}",
                    text: ("${it.lname} ${it.fname} ${it.pname}").trim(),
					iconCls: 'emp_icon',
                    leaf: 'true'
            ]
        }
    }

    def getJobPositions = {
        return Employee.constraints.jobPosition.inList.collect {
            [
                    data: "${it.value}"
            ]
        }
    }

    def getElement(params) {
        def employee = Employee.get(params.get('employeeId').trim())
        return [
                id: employee.id,
                type: 'employee',
                lname: employee.lname,
                fname: employee.fname,
                pname: employee.pname,
                email: employee.email,
                birthDate: employee.birthDate,
                jobPosition: employee.jobPosition,
                project: employee.project.name
        ]
    }

    def addElement(params) {
        def project = Project.get(params.get("projectId").trim())
        def newEmployee = new Employee()

        for (Employee emp : Employee.list()) {
            if (emp.email.trim().equalsIgnoreCase(params.get('email-inputEl').trim()))
                return ['success': false, 'message': 'Такой email уже зарегистрирован']
        }
        if (new Date().parse('dd.MM.yyyy', params.get('birthDate-inputEl').trim()) >= new Date() - 6570)
            return ['success': false, 'message': 'Сотрудник не должен быть моложе 18 лет']

        newEmployee.lname = params.get('lname-inputEl').trim()
        newEmployee.fname = params.get('fname-inputEl').trim()
        newEmployee.pname = params.get('pname-inputEl').trim()
        newEmployee.jobPosition = params.get('jobPosition-inputEl').trim()
        newEmployee.birthDate = new Date().parse('dd.MM.yyyy', params.get('birthDate-inputEl').trim())
        newEmployee.email = params.get('email-inputEl').trim()
        newEmployee.project = project

        if (newEmployee.save())
            return ['success': true, 'message': "Сотрудник <b>${newEmployee.lname} ${newEmployee.fname} ${newEmployee.pname}</b> добавлен"]
        return ['success': false, 'message': 'Не удалось добавить нового сотрудника']
    }

    def modElement(params) {
        def modEmployee = Employee.get(params.get("employeeId").trim())
        def final modEmployeeFio = (modEmployee.lname + ' ' + modEmployee.fname + ' ' + modEmployee.pname).trim()
        def newProjectId
        def employeeInfoChanged = false

        for (Employee employee : Employee.list()) {
            if (employee.id == modEmployee.id) {
                if (!employee.lname.trim().equals(params.get('lname-inputEl').trim()) ||
                        !employee.fname.trim().equals(params.get('fname-inputEl').trim()) ||
                        !employee.pname.trim().equals(params.get('pname-inputEl').trim()) ||
                        !employee.jobPosition.trim().equals(params.get('jobPosition-inputEl').trim()) ||
                        employee.birthDate != new Date().parse('dd.MM.yyyy', params.get('birthDate-inputEl').trim()) ||
                        !employee.email.trim().equalsIgnoreCase(params.get('email-inputEl').trim())) {
                    employeeInfoChanged = true
                }
                try {
                    newProjectId = (params.get('project-inputEl').trim() as long)
                    if (modEmployee.project.id != newProjectId)
                        employeeInfoChanged = true
                } catch (NumberFormatException ignored) {}
            } else if (employee.email.trim().equalsIgnoreCase(params.get('email-inputEl').trim()))
                return ['success': false, 'message': 'Такой email уже зарегистрирован']
        }
        if (new Date().parse('dd.MM.yyyy', params.get('birthDate-inputEl').trim()) >= new Date() - 6570)
            return ['success': false, 'message': 'Сотрудник не должен быть моложе 18 лет']
        if (!employeeInfoChanged)
            return ['success': false, 'message': 'Ничего не изменилось']

        modEmployee.lname = params.get('lname-inputEl').trim()
        modEmployee.fname = params.get('fname-inputEl').trim()
        modEmployee.pname = params.get('pname-inputEl').trim()
        modEmployee.jobPosition = params.get('jobPosition-inputEl').trim()
        modEmployee.birthDate = new Date().parse('dd.MM.yyyy', params.get('birthDate-inputEl').trim())
        modEmployee.email = params.get('email-inputEl').trim()
        if (newProjectId != null)
            modEmployee.project = Project.findById(newProjectId)

        if (modEmployee.save()) {
            def message = "Сотрудник <b>${modEmployeeFio}</b> изменен. Текущее ФИО - <b>${modEmployee.lname} ${modEmployee.fname} ${modEmployee.pname}</b>"
            if ((modEmployee.lname + ' ' + modEmployee.fname + ' ' + modEmployee.pname).trim().equalsIgnoreCase(modEmployeeFio))
                message = "Сотрудник <b>${modEmployeeFio}</b> изменен"
            return ['success': true, 'message': message, 'modEmployee': 'Emp_' + modEmployee.id, 'projectAncestor': 'Proj_' + modEmployee.project.id, 'divisionAncestor': 'Div_' + modEmployee.project.division.id]
        }
        return ['success': false, 'message': "Не удалось изменить сотрудника <b>${modEmployeeFio}</b>"]
    }

    def delElement(params) {
        def delEmployee = Employee.get(params.get("employeeId").trim())
        def final delEmployeeFio = delEmployee.lname + ' ' + delEmployee.fname + ' ' + delEmployee.pname
        if (delEmployee.delete())
            return ['success': true, 'message': "Сотрудник <b>${delEmployeeFio}</b> удален"]
        return ['success': false, 'message': "Не удалось удалить сотрудника <b>${delEmployeeFio}</b>"]
    }
}